import BaseApi from './BaseApi'
import {ABNORMAL,LOGIN_OUT,SUCCESS} from '../../common/config/code'
import {symbolContext} from '../../decorator/decorator'
import { Notification } from 'element-ui';
class Api extends BaseApi {
  constructor (target) {
    super()
    if(target){
      this.context.call(this,target)
    }

  }
  //由于装饰得到的是Api这个类而不是实例我们需要一些特殊的方法来实现
  context(target){
    target.prototype[symbolContext]=this
  }
  initNotice () {
    this.Notice=Notification
    // dosomething
  }
  request (config) {
    return config;
  }
  response (response) {
    return response;
  }
  reject (error) {
    console.error(error)
  }
  //用户未登录
  loginOut(){
    App.$router.push({
      name:'login'
    })
  }
  before () {}
  after () {}
  abnormal (param,res) {
    this.showNotice(param,res,'温馨提示','warning')
  }
  error (param,res) {
    this.showNotice(param,res,'不好了','error')
  }
  showNotice(param,res,title,type='info'){
    this.Notice[type]({
      title,
      message:res.message,
    })
  }
  async common (param) {
    let _config = Object.assign({}, param)
    await this.before()
    let res;
    try {
      res = await this.axios(param.url, _config)
      res=(res&&res.data)?res.data:null;

      if ( ABNORMAL.includes(res.code)) {

        param.abnormal ? param.abnormal(param,res) : this.abnormal(param,res)
      }else if (LOGIN_OUT.includes(res.code)){
        this.loginOut();
      } else if(SUCCESS.includes(res.code)){
        (param.successNotice)?this.showNotice(param,res,'恭喜你','success'):'';
        param.success?param.success(res):''
      }else{
        param.error ? param.error(res,param) : this.error(param,{message:"程序在开小差"})
      }
    } catch (e) {
      console.info(e)
      param.error ? param.error(res,param) : this.error(param,{message:"程序在开小差"})
    }
    await this.after()
    return res
  }
}
export default Api
